import React, { useState, useEffect } from "react";
import { Button, Upload, message, Image, Flex, } from "antd";
import { UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import useUpload from "./useUpload";
import './index.scss';
import { ACCEPT_TYPE } from '../../../../utils/constant';
import { useTranslation } from 'react-i18next';
import { debounce } from "../../../../utils/commonUtil";
import { apiSysBatchUpload } from '../../../../services/common'
import _ from 'lodash';
import DeleteConfirm from '../../../Components/DeleteConfirm';

const UploadFile = ({
  // 上传按钮文案
  btnText,
  // 附件类型
  acceptType,
  // 上传或删除更新
  uploadUpdateFn,
  // 是否disabled
  disabled,
  // fileList
  fileListData,
  // 最大上传数量
  maxCount = 20,
  //上传前过滤方法
  beforeFilterFn,
  //隐藏上传文件
  isHide = false,
  //自定义上传接口方法
  uploadApiFn
}) => {
  const { t } = useTranslation();
  const { TYPE, VERIFIED } = acceptType;
  const acceptText = TYPE?.join(',');

  const [fileList, setFileList] = useState(fileListData || []);
  // 每次新上传的文件
  const [appendFileList, setAppendFileList] = useState(fileListData || []);

  useEffect(() => {
    // console.log("fileListData", fileListData, fileList)
    setFileList(fileListData);
  }, [fileListData]);

  const onRemove = ({ file, fileList }) => {
    DeleteConfirm({
      t,
      title: t('common.deleteFileMsg'),
      onOk() {
        uploadUpdateFn([], true);
      }
    });
  }

  const MAX_SIZE = 1;
  const beforeUpload = (file, list) => {
    console.log("🚀 ~ beforeUpload ~ list:", list)
    // 判断最后一个文件是否添加进来
    if (file?.uid === list?.[list?.length - 1]?.uid) {
      // 判断上传数量
      if (fileList?.length + list?.length > maxCount) {
        message.error(t('common.uploadTipsSum'));
        return false;
      };
      let filterList = list
      if (beforeFilterFn) {
        filterList = beforeFilterFn(list)
        if (!filterList || filterList.length === 0) {
          return false
        }
      }
      // 文件总大小
      let filesSize = 0;
      // 判断文件格式
      for (let fileItem of filterList) {
        const type = fileItem?.type || fileItem?.name?.split('.')?.pop()?.toLowerCase();
        filesSize += fileItem.size;
        const isValidType = VERIFIED?.includes(type);
        if (!isValidType && VERIFIED?.length !== 0) {
          message.error(t('common.uploadTips', { type: TYPE }));
          return false;
        };
      };
      // 判断文件总大小 GB
      if (filesSize / 1024 / 1024 / 1024 > MAX_SIZE) {
        message.error(t('common.uploadTipsSize'));
        return false;
      };
      setAppendFileList(filterList);
      return true;
    } else {
      return false;
    }
  };

  const customRequest = debounce(async () => {
    const param = new FormData();

    appendFileList.map((file) => {
      param.append('files', file);
    });
    console.log("param", param.get("files"))

    if (uploadApiFn) {
      const res = await uploadApiFn(param)
      uploadUpdateFn(res)
    } else {
      apiSysBatchUpload(param).then((res) => {
        if (res?.data) {
          const resFiles = res?.data?.data?.items?.map((item, index) => {
            return {
              ...item,
              uid: index,
              name: item?.attachmentName,
              status: 'done',
              url: item?.attachmentUrl,
            }
          });
          uploadUpdateFn([...fileList, ...resFiles]?.map(item => {
            return {
              ..._.omit(item, ['uid', 'name', 'status', 'url'])
            }
          }));
        };
      });
    }

  }, 300);


  return (
    <>
      <Upload
        className="uploadFileWrap"
        defaultFileList={fileList}
        fileList={fileList}
        accept={acceptText}
        multiple={true}
        beforeUpload={beforeUpload}
        customRequest={customRequest}
        maxCount={maxCount}
        disabled={disabled || isHide}
        itemRender={(originNode, file) => {
          return file.status === 'done' ? <Flex justify='space-between' className={disabled ? 'uploadFile disabled' : 'uploadFile'}>
            <span className='name'>{file.url}</span>
            {!disabled && <DeleteOutlined className='icon' onClick={() => onRemove(file, fileList)} />}

          </Flex> : null
        }}
      >
        {fileList.length < 1 && <Button style={{ visibility: isHide ? 'hidden' : 'initial' }} disabled={disabled} icon={<UploadOutlined />} >{btnText}</Button>}
      </Upload>

    </>

  )
}

export default UploadFile;